<?php

namespace AdminBundle\Controller;

use AdminBundle\Services\AdminStrategy;
use AdminBundle\Services\Menu;
use AdminBundle\Services\s_admin_auth;
use BaseBundle\Controller\BaseController;
use RedUnicorn\SymfonyKernel\Unicorn;

class AdminController extends BaseController
{
    protected $defMark = null;

    /**
     * @var AdminStrategy 后台策略
     */
    public $adminStrategy = null;

    /**
     * 入口方法
     *
     * @param $return_type
     * @param bool $is_login
     * @return bool|\Symfony\Component\HttpFoundation\Response
     */
    public function inlet($return_type, $is_login = true)
    {
        $r = parent::inlet($return_type, $is_login);
        if($r !== true){
            return $r;
        }

        // 机制
        $this->setPlatform($this->getParameter('platform_admin'));

        if($this->container->hasParameter('session_type') && $this->getParameter('session_type') == 'redis'){
            if(self::$request->cookies->has('PHPREDISKEY') && self::$request->getCurrentRouteName() == 'admin_index') {
                return $this->noLogin('登陆超时！');
            }
        }

        $this->adminStrategy = new AdminStrategy($this->container);

        if(!empty($this->defMark)) {
            if (!empty($this->adminStrategy->getMark())) {
                $this->adminStrategy->setMenuTag($this->adminStrategy->getMark());
            } else {
                $this->adminStrategy->setMenuTag($this->defMark);
            }
        }

        if ($is_login == false) {
            return true;
        }

        // 登陆权限
        $s_admin_auth = new s_admin_auth($this->container);
        $res = $s_admin_auth->inletCheck();

        if ($res !== true) {
            return $this->noLogin('登陆超时！');
        }

        // 权限验证
        if (!$this->permission($this->getUserId(),self::$request->getCurrentRouteName())){
            return $this->noLogin('权限不足！');
        }

        // 存入用户拥有权限
        $this->savePermissionToRequest($this->getUserId());

        // 获取菜单
        if(Unicorn::getReturnType() == $this->getParameter('return_page')) {
            $menu = new Menu($this->container);
            self::$request->query->set('menus', $menu->getMenus($this->getUserId()));
        }

        return true;
    }


    public function permission($user_id, $route)
    {
        $permissionName = $this->getPermissionName($route);

        //公共路由
        $public_permission[] =  'admin_index';//登录页面
        $public_permission[] =  'admin_auth_login';//登录
        $public_permission[] =  'admin_auth_logout';//退出
        $public_permission[] =  'admin_service_del';//批量删除
        $public_permission[] =  'admin_service_import';//批量删除
        $public_permission[] =  'admin_auth_editPwdPage';//修改密码页面
        $public_permission[] =  'admin_auth_editPwd';//修改密码操作

        //权限不足
        if (!in_array($route,$public_permission) && !$this->can($user_id, $permissionName)){
            return false;
        }

        return true;
    }

    /**
     * 保存权限入request
     *
     * @param $userId
     * @return bool
     */
    public function savePermissionToRequest($userId)
    {
        if (!$this->hasPermissionCache($userId)){
            $user_has_permissions = $this->getPermissionsByUser($userId);
            $this->setPermissionCache($user_has_permissions,$userId);
        }

        $user_has_permissions = $this->getPermissionCache($userId);
        if (!$this->isSuperAdmin($userId)){
            self::$request->query->set('user_has_permissions', $user_has_permissions);
        }else{
            self::$request->query->set('user_has_permissions', 'all');
        }

        return true;
    }

    /**
     * 判断是否超级管理员
     *
     * @param $userId
     * @return bool
     */
    public function isSuperAdmin($userId)
    {
        return $userId == $this->getParameter('super_id');
    }

    /**
     * @param $userId
     * @return bool
     */
    public function hasPermissionCache($userId)
    {
        return $this->get('unicorn.sessions')->has('hasPermissionCache'.$userId);
    }

    /**
     * 设置权限缓存
     *
     * @param $hasPermissionCache
     * @param $userId
     */
    public function setPermissionCache($hasPermissionCache,$userId)
    {
        return $this->get('unicorn.sessions')->set('hasPermissionCache'.$userId,$hasPermissionCache);
    }

    /**
     * 获取权限缓存
     *
     * @param $userId
     * @return mixed
     */
    public function getPermissionCache($userId)
    {
        return $this->get('unicorn.sessions')->get('hasPermissionCache'.$userId);
    }

    /**
     * 是否有权限查看
     *
     * @param $userId
     * @param $permissionName
     * @param array $params
     * @return mixed
     */
    public function can($userId, $permissionName, $params = array())
    {
        if ($this->isSuperAdmin($this->getUserId()) || !$permissionName) {
            return true;
        }

        return $this->get('rbac')->checkAccess($userId, $permissionName, $params);
    }

    /**
     * 根据route获取权限名称
     *
     * @param $routeName
     * @return mixed
     */
    public function getPermissionName($routeName)
    {
        $routeCollection = $this->get('router')->getRouteCollection();

        return $routeCollection->get($routeName)->getOption('permission_name');
    }

    /**
     * 获取用户权限
     *
     * @param $userId
     * @return mixed
     */
    public function getPermissionsByUser($userId)
    {
        // TODO redis缓存
        if ($this->isSuperAdmin($this->getUserId())) {
            return $this->get('rbac')->getPermissions();
        }

        return $this->get('rbac')->getPermissionsByUser($userId);
    }

    public function noLogin($message = '登陆凭证失效'){

        if(Unicorn::getReturnType() == $this->getParameter('return_page')){
            return $this->goRoute('admin_index');
        }

        return $this->response($message, $this->getParameter('error_code_not_logged'), ['go_url' => $this->getUrl('admin_index')]);
    }
}
